import type { TabsState, Tabs } from './types'
import { defineStore } from 'pinia'
import { store } from '@/store'
import { router } from '@/router'

export const useTabsStore = defineStore('tabs', {
  state: (): TabsState => ({
    tabsMenuValue: '/system/user',
    tabsMenuList: []
  }),
  getters: {
    getTabsMenuValue(): string {
      return this.tabsMenuValue
    },
    getTabsMenuList(): Tabs[] {
      return this.tabsMenuList
    }
  },
  actions: {
    addTabs(tabItem: Tabs) {
      if (['/403', '/404'].includes(tabItem.path)) return

      const tabInfo = {
        title: tabItem.title,
        path: tabItem.path,
        close: tabItem.close,
        name: tabItem.name
      }

      if (this.tabsMenuList.every((item) => item.path !== tabItem.path)) {
        this.tabsMenuList.push(tabInfo)
      }

      this.setTabsMenuValue(tabItem.path)
    },

    removeTabs(tabPath: string, name: string) {
      let tabsMenuValue = this.tabsMenuValue
      const tabsMenuList = this.tabsMenuList
      if (tabsMenuValue === tabPath) {
        tabsMenuList.forEach((item, index) => {
          if (item.path !== tabPath) return
          const nextTab = tabsMenuList[index + 1] || tabsMenuList[index - 1]
          if (!nextTab) return
          tabsMenuValue = nextTab.path
          router.push(nextTab.path)
        })
      }
      this.tabsMenuValue = tabsMenuValue
      this.tabsMenuList = tabsMenuList.filter((item) => item.path !== tabPath)
    },

    changeTabs(tabItem: Tabs) {
      this.tabsMenuList.forEach((item) => {
        if (item.title === tabItem.title) router.push(item.path)
      })
    },

    setTabsMenuValue(tabsMenuValue: string) {
      this.tabsMenuValue = tabsMenuValue
    },
    setTabsMenuList(tabsMenuList: Tabs[]) {
      this.tabsMenuList = tabsMenuList
    }
  },
  persist: [
    {
      key: 'tabStore',
      storage: window.sessionStorage,
      // 用于指定 state 中哪些数据需要被持久化。[] 表示不持久化任何状态，undefined 或 null 表示持久化整个 state。
      // paths: undefined, // 或者写 ["token", "userInfo"]
    },
  ] as any,
})

// 需要在设置之外使用
export function useTabsStoreWithOut() {
  return useTabsStore(store)
}